package example.demo.controller;

import example.demo.netty.JsonMessage;
import example.demo.netty.NettyClientStart;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/netty-client")
public class NettyClientController {
    @Autowired
    NettyClientStart nettyClientStart;

    /*
      http://localhost:9777/netty-client/sendAndReceive/wahaha
     */
    @RequestMapping("/sendAndReceive/{message}")
    public JsonMessage sendAndReceive(@PathVariable String message) throws Exception {
        Channel channel = nettyClientStart.getChannel();
        channel.writeAndFlush(new JsonMessage(message, "client-request"));
        JsonMessage exchange = null;
        try {
            exchange = NettyClientStart.sendAndReceiveMessage.exchange(null);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return exchange;
    }

}
